package com.lp.zyll.aop;


import com.alibaba.fastjson.JSONObject;
import com.lp.zyll.domain.LpLog;
import com.lp.zyll.service.LpLogService;
import com.lp.zyll.util.StringUtils;
import com.lp.zyll.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    LpLogService logService;

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);
    ThreadLocal<Long> currentTime = new ThreadLocal<>();

//    public LogAspect(SysLogService logService) {
//        this.logService = logService;
//    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.lp.zyll.aop.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        LpLog log = new LpLog("INFO",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //获取请求参数
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> parameterMap = new HashMap<>();
        while (enumeration.hasMoreElements()){
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter,request.getParameter(parameter));
        }
        if (parameterMap.size()>0){

            log.setParams(JSONObject.toJSONString(parameterMap));
        }else {
            log.setParams(JSONObject.toJSONString(joinPoint.getArgs()[0]));
        }

        logService.save("", StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, log);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        LpLog log = new LpLog("ERROR",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        //获取请求参数
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> parameterMap = new HashMap<>();
        while (enumeration.hasMoreElements()){
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter,request.getParameter(parameter));
        }
        if (parameterMap.size()>0){
            log.setParams(JSONObject.toJSONString(parameterMap));
        }else {
            log.setParams(JSONObject.toJSONString(joinPoint.getArgs()[0]));
        }

        log.setExceptionDetail(ThrowableUtil.getStackTrace(e));

        logService.save("", StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, log);
    }

}
